package com.yuexun.beilunpatient.ui.main.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.BaseKJActivity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.utils.FileUtils;
import com.yuexun.beilunpatient.view.ProgressWebView;
import com.yuexun.beilunpatient.widget.LoadingDialog;

import org.kymjs.kjframe.ui.ViewInject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/5/9 0009.
 */

public class Act_Webview extends BaseKJActivity implements View.OnKeyListener {

    @Bind(R.id.webview)
    ProgressWebView webview;
    @Bind(R.id.title)
    TextView title;

    Handler handler = new Handler(Looper.getMainLooper());
    private String mUrl;

    private Handler handler_down;
    private LoadingDialog loadingDialog;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_webview);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        title.setText(getIntent().getExtras().getString("title"));

        loadingDialog = new LoadingDialog(aty);
        loadingDialog.setCancelable(true);
        loadingDialog.setCanceledOnTouchOutside(false);

        handler_down = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        loadingDialog.show();
                        break;
                    case 1:
                        loadingDialog.dismiss();
                        break;
                }
            }
        };

        mUrl = getIntent().getStringExtra("url");
//        mUrl="http://61.175.221.118:8080/tzgs/pages/html/govfile.html?sessionUuid=7dd4b384e5484d8e8a8dd2b9ad821cbd";
        init_web();
        try {
            webview.loadUrl(mUrl);
        } catch (Exception e) {
            Toast.makeText(aty, "信息加载错误", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void init_web() {
        webview.setOnKeyListener(this);
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webview.setInitialScale(100);
        webview.setWebViewClient(new CustomWebViewClient());
//        webview.setWebChromeClient(new CustomWebChromeView());

        webview.addJavascriptInterface(new DownFile(), "downFileJava");

        webview.addJavascriptInterface(new JObjectBack(), "bac");
//        webview.setSaveEnabled(false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.title_back)
    public void onViewClicked() {
        finish();
    }


    private class CustomWebViewClient extends WebViewClient {


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("tel:")) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                return true;
            } else {
//                view.loadUrl(url);
                return false;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }


        @Override
        public void onPageFinished(WebView view, String url) {

            super.onPageFinished(view, url);
        }
    }


    class JObjectBack {
        @JavascriptInterface
        public void back() {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            });
        }
    }

    /* private Request buildPostRequest(String url, Param[] params)
     {
         if (params == null)
         {
             params = new Param[0];
         }
         FormEncodingBuilder builder = new FormEncodingBuilder();
         for (Param param : params)
         {
             builder.add(param.key, param.value);
         }
         RequestBody requestBody = builder.build();
         return new Request.Builder()
                 .url(url)
                 .post(requestBody)
                 .build();
     }*/
    class DownFile {
        @JavascriptInterface
        public void DownFileJava(String prefix, String fileName) {
            final String strUrl = AppConfig.WEB_FILE + prefix;
            download(strUrl, fileName);
        }

        @JavascriptInterface
        public void DownFileJavaWithURL(String url) {
            //https://51wangzhen.com/hsey/UploadFile/201801/file/手术资格准入申请表.doc
            String[] name = url.split("file/");
            download(url, name[1]);
        }

        private void download(final String strUrl, final String fileName) {
            ViewInject.toast("开始下载");
            Message msg = new Message();
            msg.what = 0;
            handler_down.sendMessage(msg);

            OkHttpClient client = new OkHttpClient();
            client.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
            Request request = new Request.Builder()
                    .url(strUrl)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    System.out.println(e.toString());
                    ViewInject.toast("下载失败");
                    Message msg = new Message();
                    msg.what = 1;
                    handler_down.sendMessage(msg);
                }

                @Override
                public void onResponse(final Response response) throws IOException {

                    InputStream is = null;
                    byte[] b = new byte[1024];
                    FileOutputStream fos = null;
                    int len = 0;
                    try {
                        is = response.body().byteStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    final File file = org.kymjs.kjframe.utils.FileUtils.getSaveFile(AppConfig.FILE_CONTENT, fileName);
                    String end = fileName.substring(fileName.indexOf(".") + 1, fileName.length()).toLowerCase();
                    fos = new FileOutputStream(file);
                    if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                            || end.equals("jpeg") || end.equals("bmp")) {
                        BufferedOutputStream bos = new BufferedOutputStream(fos);
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                        is.close();
                        bos.flush();
                        bos.close();

                    } else {
                        while ((len = is.read(b)) != -1) {
                            fos.write(b, 0, len);
                        }
                        fos.flush();
                        is.close();
                        fos.close();
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                FileUtils fileUtils = new FileUtils(aty);
                                final Intent intent = fileUtils.openFile(file.getAbsolutePath());
                                startActivity(intent);
                            } catch (Exception e) {
                                Toast.makeText(aty, "没有找到打开该文件的应用", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                    Message msg = new Message();
                    msg.what = 1;
                    handler_down.sendMessage(msg);
                }
            });
        }
    }

    @Override
    public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
